package com.example.testappwidget.adpter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.LinearLayout
import com.example.testappwidget.R
import com.example.testappwidget.view.MyWidgetHostView

/**
 *Author: chinadragon
 *Time: 2024/4/6
 */
class MyListWidgetAdapt(val mContext: Context, var mList: MutableList<MyWidgetHostView> = mutableListOf()): BaseAdapter() {
    override fun getCount(): Int {
        return mList.size
    }

    override fun getItem(position: Int): Any {
        return mList[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var viewHolder: ViewHolder?  = null
        var view: View? = null
        if (convertView == null){
            view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false)
            val linearLayout: LinearLayout = view.findViewById(R.id.parent_linearlayout)
            viewHolder = ViewHolder(linearLayout)
            view.setTag(viewHolder)
        }else{
            view = convertView
            viewHolder = view?.getTag() as ViewHolder
        }

        val myWidgetHostView: MyWidgetHostView = mList.get(position)
        myWidgetHostView.layoutParams = MyWidgetHostView.MyLayoutParams(myWidgetHostView.mWidth, myWidgetHostView.height)

        viewHolder.linearLayout!!.apply {
            removeAllViews()
            addView(myWidgetHostView, layoutParams)
        }
        viewHolder.linearLayout!!.requestLayout()

        return view!!
    }

    fun setLists(list: MutableList<MyWidgetHostView>){
        if (mList.size > 0){
            mList.clear()
        }
        mList.addAll(list)
    }

    class ViewHolder(var linearLayout: LinearLayout? = null){


    }
}